package com.school.view.model;

import java.util.Vector;

import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;

import com.school.view.beans.ViewTableBean;

public class StudentTableModel implements TableModel {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2637191468741726256L;

	private Vector<ViewTableBean> data = new Vector<ViewTableBean>();
	private Vector<TableModelListener> listeners = new Vector<TableModelListener>();

	private String[] columnNames = { "Vorname", "Name", "Note" };

	public void addViewTableBean(ViewTableBean tableBean) {
		int index = data.size();
		data.add(tableBean);

		TableModelEvent event = new TableModelEvent(this, index, index,
				TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT);

		for (int i = 0; i < listeners.size(); i++) {
			listeners.get(i).tableChanged(event);
		}
	}

	@Override
	public int getColumnCount() {
		return 3;
	}

	@Override
	public int getRowCount() {
		return data.size();
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		ViewTableBean tableBean = data.get(rowIndex);

		switch (columnIndex) {
		case 0:
			return tableBean.getVorname();
		case 1:
			return tableBean.getName();
		case 2:
			return tableBean.getNote();
		default:
			return null;
		}
	}

	@Override
	public boolean isCellEditable(int rowIndex, int columnIndex) {
		return false;
	}

	@Override
	public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
		throw new UnsupportedOperationException(
				"Function is not supported in this context");
	}

	@Override
	public Class<?> getColumnClass(int columnIndex) {
		Object object = getValueAt(0, columnIndex);
		if (object != null) {
			return object.getClass();
		}
		return Object.class;
	}

	@Override
	public String getColumnName(int column) {
		return columnNames[column];
	}

	@Override
	public void addTableModelListener(TableModelListener l) {
		listeners.add(l);
	}

	@Override
	public void removeTableModelListener(TableModelListener l) {
		listeners.remove(l);
	}

}
